package org.example.lesson;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPThreadPoolServer extends TCPEchoServer{
    /**
     * 构造方法
     * @param port
     * @throws IOException
     */
    public TCPThreadPoolServer(int port) throws IOException {
        super(port);
    }

    @Override
    public void start() throws IOException {
        System.out.println("服务器已启动，等待客户端连接.");
        //创建一个线程池
        ThreadPoolExecutor threadPool=new ThreadPoolExecutor(3,10,1, TimeUnit.SECONDS,new LinkedBlockingDeque<>(1));
        //循环处理客户端连接
        while(true){
            //接收客户端连接
            Socket clientSocket=socket.accept();
            //把处理连接的操作加入了线程池中
            threadPool.submit(()->{
                //子线程中处理连接数据
                processConnections(clientSocket);
            });
        }
    }

    public static void main(String[] args) throws IOException {
        TCPThreadPoolServer server=new TCPThreadPoolServer(9090);
        server.start();
    }
}
